package yana.tpe.servlets.task5.controller;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.LoggerFactory;
import yana.tpe.servlets.task5.domain.domains.User;
import yana.tpe.servlets.task5.services.UserService;

@Controller
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String foo() {
        logger.debug("Try to get root");
        return "redirect:user";
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public ModelAndView get(@RequestParam(required=false, value="order", defaultValue="id") String order,
            @RequestParam(required=false, value="ascending", defaultValue="true") boolean ascending) {
        logger.debug("Try to get User");
        ModelAndView mav = new ModelAndView();
        mav.setViewName("users");
        mav.addObject("users", userService.getOrderedList(order, ascending));
        mav.addObject("user", new User());
        mav.addObject("order", order);
        mav.addObject("ascending", ascending);
        return mav;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String add(@ModelAttribute("user") User user, BindingResult result) {
        logger.debug("Try to add User {}", user);
        if (result.hasErrors()) {
            return "/users";
        }

        userService.saveOrUpdate(user);

        return "redirect:/user";
    }

    @RequestMapping(value = "/user/{id}/edit", method = RequestMethod.GET)
    public String edit(@PathVariable String id, Model model) {
        logger.debug("Try to edit User [id={}]", id);
        User user = userService.get(Integer.parseInt(id));

        model.addAttribute("user", user);

        return "/users";
    }

    @RequestMapping(value = "/user/{id}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable String id, Model model) {
        logger.debug("Try to delete User [id={}]", id);
        User user = userService.get(Integer.parseInt(id));

        userService.delete(user);
        return "redirect:/user";
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
}
